package com.haohan.cloud.scm.common.tools.util;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;

/**
 * @author dy
 * @date 2019/10/22
 */
@Slf4j
@UtilityClass
public class PinYin4jUtils {

    private static HanyuPinyinOutputFormat format;

    static {
        format = new HanyuPinyinOutputFormat();
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
    }

    /**
     * 获取字符串汉字的  拼音首字母
     *
     * @param str
     * @return
     */
    public static String fetchFirst(CharSequence str) {
        return fetchPinYin(str, true);
    }

    /**
     * 获取字符串 全拼
     *
     * @param str
     * @return
     */
    public static String fetchPinYin(CharSequence str) {
        return fetchPinYin(str, false);
    }

    /**
     * 获取字符串的拼音
     *
     * @param str
     * @param firstFlag 是否只要首字母
     * @return
     */
    private static String fetchPinYin(CharSequence str, boolean firstFlag) {
        int length;
        if (null == str || (length = str.length()) == 0) {
            return null;
        }
        StringBuilder py = new StringBuilder();
        String one;
        for (int i = 0; i < length; i++) {
            one = fetchPinYin(str.charAt(i), firstFlag);
            if (null != one) {
                py.append(one);
            }
        }
        return py.toString();
    }

    /**
     * 获取1个汉字的拼音首字母
     *
     * @param c
     * @return
     */
    public static String fetchFirst(char c) {
        return fetchPinYin(c, true);
    }

    /**
     * 提取1个汉字的全拼
     *
     * @param c
     * @return
     */
    public static String fetchPinYin(char c) {
        return fetchPinYin(c, false);
    }

    private static String fetchPinYin(char c, boolean firstFlag) {
        String[] pyChars;
        try {
            pyChars = PinyinHelper.toHanyuPinyinStringArray(c, format);
            if (pyChars != null && pyChars.length > 0) {
                String py = pyChars[0];
                return firstFlag ? py.substring(0, 1) : py;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
